import { getUserMenuList } from '@/api/user'
import BasicLayout from '@/layouts/BasicLayout.vue'
import router, { constantRouterMap } from '@/router'
import { isResultSuccess } from '@/util/http'
import Logger from '@/util/log'
import { defineStore } from 'pinia'
import { RouterView, type RouteRecordRaw } from 'vue-router'
import { useProfileStore } from './profile'
const modules = import.meta.glob('../views/**/*.vue') // vite 动态导入所有的 .vue 文件，用于动态生成路由数据，需要 vite 插件 vite-plugin-pages 和 vite-plugin-singleto

export const useMenuStore = defineStore('menu', {
  state: () => ({
    menuList: [] as any[], // 菜单列表
    authList: [] as any[], // 权限列表
  }),
  actions: {
    getMenuList() {
      return this.menuList
    },
    getAuthList() {
      return this.authList
    },
    removeAll() {
      this.menuList = []
      this.authList = []
      // note：清空并初始化路由
      router.clearRoutes()
      for (const route of constantRouterMap) {
        router.addRoute(route)
      }
    },
    // todo将来考虑持久化
    async refreshMenuList() {
      // Logger.info('refreshMenuList')
      const profileStore = useProfileStore()
      const res = await getUserMenuList({
        account: profileStore.getProfile().account,
      })
      if (res && isResultSuccess(res)) {
        // 动态生成路由数据
        const accessedRoutes = filterAsyncRoutes(res.data.menuList, [])
        for (const route of accessedRoutes) {
          router.addRoute(route)
        }
        // 404 页面一定要放在最后
        const tab404 = {
          path: '/:pathMatch(.*)*',
          redirect: '/exception/404',
          meta: {
            hidden: true,
          },
        }
        router.addRoute(tab404)
        this.menuList = accessedRoutes.concat(constantRouterMap).concat(tab404)
        this.authList = res.data.authList
        // Logger.info('refreshMenuList success', this.menuList, this.authList)
      }
    },
  },
})

function isOperation(route: RouteRecordRaw) {
  return route.path === ''
}

function filterAsyncRoutes(routes: RouteRecordRaw[], roles: string[]): RouteRecordRaw[] {
  const res: Array<RouteRecordRaw> = []
  routes?.forEach((route) => {
    // 解构成为一个新值，避免修改原始数据
    const tmp = { ...route } as RouteRecordRaw
    // 按钮不需要
    if (isOperation(tmp)) {
      return
    }
    const component = tmp.component
    if (component) {
      if (typeof component === 'string' && component === 'Layout') {
        tmp.component = BasicLayout
      } else {
        // note:写法不生效，需要改成modules
        // tmp.component = () => import(`${component}`)
        tmp.component = modules[`../views/${component}`]
      }
    }
    // 菜单情形
    if (tmp.children && tmp.children.length > 0 && !isOperation(tmp.children[0])) {
      tmp.redirect = tmp.children[0].path
      if (typeof component === 'string' && component != 'Layout') {
        tmp.component = RouterView
      }
      tmp.children = filterAsyncRoutes(tmp.children, roles)
    } else {
      // 按钮情形
      tmp.children = undefined
    }

    // router.addRoute(tmp)
    res.push(tmp)
  })
  return res
}
